package org.xqh.study.leetcode.algorithm;

/**
 * @ClassName AtoiTest
 * @Description 字符串 转 int
 * @Author xuqianghui
 * @Date 2021/1/14 20:38
 * @Version 1.0
 */
public class AtoiTest {

    public static void main(String[] args) {
//        System.out.println(myAtoi("+1"));
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);

    }

    public static int myAtoi(String s) {
        s=s.trim();
        if("".equals(s)){
            return 0;
        }
        char[] array = s.toCharArray();
        int first = array[0];
        if(first != 45 && first != 43 && (first < 48 || first > 57)){
            //非数字
            return 0;
        }
        long result = 0;
        boolean negative = false;
        for(int i = 0; i < array.length; i ++){
            int tmp = array[i];
            if(i == 0 && tmp == 45){
                negative = true;
                continue;
            }

            if(i == 0 && tmp == 43){
                continue;
            }

            if(tmp < 48 || tmp > 57){
                break;
            }

            result = result * 10 + (tmp - '0');

            if(negative){
                if(-result <= Integer.MIN_VALUE){
                    return Integer.MIN_VALUE;
                }
            }else {
                if(result >= Integer.MAX_VALUE){
                    return Integer.MAX_VALUE;
                }
            }

        }
        int ret = (int)result;
        return negative ? -ret : ret;
    }

}
